package com.vshop.timingtask;

import com.alibaba.fastjson.JSON;
import com.vshop.config.dto.StringOutputConstant;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.aspecial.pushorder.request.RequestPushOrderTask;
import com.vshop.entity.aspecial.pushorder.response.ResponsePushOrderTask;
import com.vshop.service.aspecial.impl.SpecialAssistService;
import com.vshop.service.aspecial.impl.SpecialLogicServiceImpl;
import com.vshop.utils.HttpUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * 新的，新的，新的：：：
 * <p>
 * 给客户推送支付订单的定时任务
 *
 * @author lm
 * @date 2020/9/17 15:17
 */
@Configuration
@EnableScheduling
@Api(value = "帮企业同步支付数据接口")
@RestController
@Slf4j
public class ChannelResultPushOrderTask {
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    SpecialLogicServiceImpl specialService;
    @Autowired
    SpecialAssistService assistService;

    /**
     * 大阳新接口上线之后需要用此任务回调给大阳
     * <p>
     * 需要给回调的企业：大阳，掌航，星迈数码，星安达
     *
     * @Scheduled(cron = "0/5 * * * * ?")
     * @author lm
     * @date 2020/10/28 14:02
     */

    @Scheduled(cron = "0/5 * * * * ?")
    @GetMapping(value = "channelResultPushOrderTask")
    @Async

    public void execute() {
        if (autoTask) {
            task();
        }
    }

    public void task() {
        /*以下这些企业是需要去做遍历的企业编码用逗号隔开*/
        String partnerCode = "P000200,P000327,P002285,P002090";
        List<String> codeList = Arrays.asList(partnerCode.split(","));
        /*去遍历这些企业里面有么有订单数据需要去做推送的*/
        List<ServicePlanOrderRecord> recordList = specialService.queryChannelResultPushOrderWithCodeList(codeList);
        if (null == recordList || recordList.isEmpty()) {
            return;
        }
        //把数据拿出来
        for (ServicePlanOrderRecord record : recordList) {
            String noticeUrl;
            if ("P000200".equals(record.getPartnerCode())) {
                noticeUrl = specialService.queryNoticeUrl(record.getPartnerCode(), record.getDeviceCode(), record.getRequestOrderId());
                if (!checkParam(record, noticeUrl)) {
                    continue;
                }
            } else if ("P000327".equals(record.getPartnerCode()) || "P002285".equals(record.getPartnerCode()) || "P002090".equals(record.getPartnerCode())) {
                noticeUrl = "http://120.78.75.185:8088/api/Pay/CallBack";
            } else {
                return;
            }
            //拼装RequestPushOrderTask的request请求类
            RequestPushOrderTask request = formParamTeam(record);
            if (null == request) {
                continue;
            }
            //开始做推送请求
            ResponsePushOrderTask response = pushOrder(request, noticeUrl);
            if (null == response) {
                continue;
            }
            //判断响应信息
            if (StringUtils.isBlank(response.getRetCode()) || StringUtils.isBlank(response.getRetMsg())) {
                continue;
            }

            //判断回来的是不是成功的响应
            Integer noticeCount = 0;
            if ("S".equalsIgnoreCase(response.getRetCode()) && StringOutputConstant.CODE_SUCCESS.equalsIgnoreCase(response.getRetMsg())) {
                //推送成功去数据库将订单的推送状态isPartnerNotice改成1不需要再推送，原来大阳的订单都有requestOrderId可以用这个作为订单标识，现在有的订单没有这个单号，我们用orderNo来标识
                noticeCount = specialService.updateNoticeRecord(record.getPartnerCode(), record.getDeviceCode(), record.getPayId(), record.getOrderNo());
            }
            if (0 == noticeCount) {
                continue;
            } else {
                log.info("领科支付单号：" + record.getPayId() + ";iccId：" + record.getDeviceCode() + ":回调成功");
            }
        }
    }

    /**
     * 开始推送订单操作
     *
     * @param request
     * @param noticeUrl
     * @return
     */
    private ResponsePushOrderTask pushOrder(RequestPushOrderTask request, String noticeUrl) {
        // 开始组装json
        String requestStr = JSON.toJSONString(request);
        log.info("领科推送【订单】请求：" + requestStr);
        // 发送post请求，并接收返回结果
        String returnStr = HttpUtil.httpPost(noticeUrl, requestStr);
        log.info("url=" + noticeUrl);

        log.info("渠道接收【订单】响应：" + returnStr);
        ResponsePushOrderTask re = JSON.parseObject(returnStr, ResponsePushOrderTask.class);
        return re;
    }

    /**
     * 拼装RequestPushOrderTask的request请求类
     *
     * @param record
     * @return
     */
    private RequestPushOrderTask formParamTeam(ServicePlanOrderRecord record) {
        RequestPushOrderTask request = new RequestPushOrderTask();
        request.setPartnerCode(record.getPartnerCode());
        request.setDeviceCode(record.getDeviceCode());
        request.setMark(record.getMark());
        request.setServicePlanShowName(record.getServicePlanShowName());
        request.setOrderPeriod(record.getOrderPeriod() + assistService.setUpOrderPeriodUnit(record.getPackageType()));
        request.setPayId(record.getPayId());
        request.setRequestOrderId(record.getRequestOrderId());
        request.setPayType(assistService.setUpOrderPayType(record.getPayType()));
        request.setPayAmount(record.getPayAmount());
        request.setPayCurrency(record.getPayCurrency());
        request.setPayRst(record.getPayRst());
        request.setPayResultDate(record.getPayResultDate());
        return request;
    }

    /**
     * 验证ServicePlanOrderRecord和secret参数
     *
     * @param record
     * @return
     */
    private boolean checkParam(ServicePlanOrderRecord record, String noticeUrl) {
        boolean flag = true;
        if (StringUtils.isBlank(noticeUrl)) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPartnerCode())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getDeviceCode())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getMark())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getServicePlanShowName())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getOrderPeriod())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPayId())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getRequestOrderId())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPayType())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPayAmount())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPayCurrency())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPayRst())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPayResultDate())) {
            flag = false;
        }
        return flag;
    }

}
